﻿using DataTurnClient.ViewModel;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataTurnClient.Controls
{
    public partial class RouteView : UserControl, IViewFor<RouteViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (RouteViewModel)value;
        }

        public RouteViewModel ViewModel { get; set; }
        public RouteView()
        {
            InitializeComponent();
            InitBindings();
        }

        private void InitBindings()
        {
            ViewModel = new RouteViewModel();
            this.WhenActivated(d =>
            {
                this.OneWayBind(ViewModel,
                    vm => vm.RouteList,
                    v => v.metroGrid1.DataSource
                    ).DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.RouteLine.Ip,
                    v => v.input1.Text
                    ).DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.RouteLine.Port,
                    v => v.input2.Text
                    ).DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.RouteLine.Path,
                    v => v.input3.Text
                    ).DisposeWith(d);

                this.badge1.Events().Click.Do(x =>
                {
                    this.Dispose();
                }).Subscribe().DisposeWith(d);

                this.Events().Load.Do(x =>
                {
                    ViewModel.SelectLineCommand.Execute().Subscribe();
                }).Subscribe();

                this.metroLink2.Events().Click.Do(x =>
                {
                    ViewModel.CreateLineCommand.Execute().Subscribe(result =>
                    {
                        if (result.Success)
                        {
                            ViewModel.SelectLineCommand.Execute().Subscribe();
                        }
                    });
                }).Subscribe().DisposeWith(d);

                this.metroLink1.Events().Click.Do(x =>
                {
                    ViewModel.DeleteLineCommand.Execute(ViewModel.RouteList[metroGrid1.CurrentRow.Index]).Subscribe(result =>
                    {
                        if (result.Success)
                        {
                            ViewModel.SelectLineCommand.Execute().Subscribe();
                        }
                    });
                }).Subscribe().DisposeWith(d);

            });
        }
    }
}
